<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>验证码API测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            text-align: center;
        }
        h1 {
            color: #333;
        }
        .captcha-container {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        img {
            border: 1px solid #ddd;
            margin: 10px 0;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .log-container {
            margin-top: 20px;
            text-align: left;
            font-family: monospace;
            white-space: pre-wrap;
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 4px;
            max-height: 300px;
            overflow-y: auto;
        }
        .error {
            color: red;
        }
        .success {
            color: green;
        }
        .info {
            color: blue;
        }
    </style>
</head>
<body>
    <h1>验证码API测试页面</h1>
    <p>这个页面专门用于测试验证码API的连接情况</p>
    
    <div class="captcha-container">
        <img id="captchaImage" alt="验证码" style="max-width: 100%; display: none;" />
        <p id="captchaToken"></p>
    </div>
    
    <button id="testCaptchaBtn">测试验证码API</button>
    
    <div class="log-container" id="logContainer"></div>
    
    <script>
        const captchaImage = document.getElementById('captchaImage');
        const captchaToken = document.getElementById('captchaToken');
        const testCaptchaBtn = document.getElementById('testCaptchaBtn');
        const logContainer = document.getElementById('logContainer');
        
        // 日志记录函数
        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = type;
            logEntry.textContent = `[${timestamp}] ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
            
            // 同时输出到控制台
            if (type === 'error') {
                console.error(message);
            } else if (type === 'success') {
                console.log('%c' + message, 'color: green');
            } else {
                console.log('%c' + message, 'color: blue');
            }
        }
        
        // 测试验证码API
        function testCaptchaApi() {
            // 清空之前的结果
            captchaImage.style.display = 'none';
            captchaToken.textContent = '';
            
            log('开始测试验证码API...');
            log(`当前页面URL: ${window.location.href}`);
            log(`浏览器: ${navigator.userAgent}`);
            
            try {
                const timestamp = new Date().getTime();
                // 直接使用后端服务的完整URL
                const url = `http://localhost:8000/api/auth/captcha?t=${timestamp}`;
                
                log(`准备发送请求到: ${url}`);
                
                // 记录请求开始时间
                const startTime = performance.now();
                
                fetch(url, {
                    method: 'GET',
                    credentials: 'include',
                    headers: {
                        'Accept': 'application/json'
                    },
                    mode: 'cors'
                })
                    .then(response => {
                        const endTime = performance.now();
                        log(`请求完成，耗时: ${Math.round(endTime - startTime)}ms`, 'info');
                        log(`响应状态码: ${response.status}`, response.ok ? 'success' : 'error');
                        
                        // 打印响应头信息
                        log('响应头信息:', 'info');
                        const headers = {};
                        response.headers.forEach((value, name) => {
                            headers[name] = value;
                            log(`  ${name}: ${value}`, 'info');
                        });
                        
                        // 检查CORS相关头
                        if (headers['access-control-allow-origin']) {
                            log(`CORS允许的源: ${headers['access-control-allow-origin']}`, 'success');
                        } else {
                            log('警告: 未检测到CORS允许源头', 'error');
                        }
                        
                        if (!response.ok) {
                            throw new Error(`HTTP错误! 状态码: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        log('成功获取验证码数据!', 'success');
                        log('返回数据: ' + JSON.stringify(data, null, 2), 'success');
                        
                        if (data && data.captchaImage && data.captchaToken) {
                            captchaImage.src = data.captchaImage;
                            captchaImage.style.display = 'block';
                            captchaToken.textContent = `验证码Token: ${data.captchaToken}`;
                            log('验证码图片显示成功!', 'success');
                        } else {
                            log('错误: 验证码数据格式不正确', 'error');
                            log('缺少的字段: ' + 
                                (data ? 
                                    ((!data.captchaImage ? 'captchaImage' : '') + 
                                     (!data.captchaToken ? ' captchaToken' : '')) : 
                                    '数据为空'), 'error');
                        }
                    })
                    .catch(error => {
                        log(`获取验证码失败: ${error.message}`, 'error');
                        log(`错误类型: ${error.constructor.name}`, 'error');
                        log(`错误堆栈: ${error.stack}`, 'error');
                        
                        if (error.message.includes('Failed to fetch')) {
                            log('\n可能的原因:', 'error');
                            log('1. 后端服务未运行', 'error');
                            log('2. 防火墙阻止了连接', 'error');
                            log('3. CORS配置不正确', 'error');
                            log('4. 浏览器安全策略限制', 'error');
                            log('5. 网络连接问题', 'error');
                        }
                    });
            } catch (e) {
                log(`捕获到异常: ${e.message}`, 'error');
                log(`异常类型: ${e.constructor.name}`, 'error');
                log(`异常堆栈: ${e.stack}`, 'error');
            }
        }
        
        // 事件监听器
        testCaptchaBtn.addEventListener('click', testCaptchaApi);
        
        // 页面加载时显示基本信息
        window.addEventListener('load', function() {
            log('页面加载完成，请点击按钮开始测试验证码API', 'info');
            log('后端服务地址: http://localhost:8000/api/auth/captcha', 'info');
            log('请确保后端服务正在运行', 'info');
        });
    </script>
</body>
</html>